<template>
  <div class="modification-management">
    <div class="header">
      <h2>档案修改申请管理</h2>
      <div class="header-buttons">
        <el-button type="primary" @click="showSubmitDialog" v-if="userRole === '普通员工' || userRole === '档案管理员'">
          <i class="el-icon-plus"></i>
          提交修改申请
        </el-button>
        <el-button type="info" @click="loadRequests">
          <i class="el-icon-refresh"></i>
          刷新
        </el-button>
      </div>
    </div>

    <!-- 修改申请列表 -->
    <el-table :data="requests" style="width: 100%" v-loading="loading">
      <el-table-column prop="archiveTitle" label="档案标题" width="200"></el-table-column>
      <el-table-column prop="applicantName" label="申请人" width="120"></el-table-column>
      <el-table-column prop="modifyContent" label="修改后内容" show-overflow-tooltip>
        <template slot-scope="scope">
          <span class="modify-content-preview">{{ scope.row.modifyContent }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="applyTime" label="申请时间" width="180">
        <template slot-scope="scope">
          {{ formatDate(scope.row.applyTime) }}
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="100">
        <template slot-scope="scope">
          <el-tag :type="getStatusType(scope.row.status)">
            {{ getStatusText(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="250">
        <template slot-scope="scope">
          <el-button size="mini" @click="viewRequest(scope.row)">查看</el-button>
          <el-button size="mini" type="primary" @click="approveRequest(scope.row)" 
                     v-if="userRole === '企业领导' && scope.row.status === 'pending'">
            审批
          </el-button>
          <el-button size="mini" type="success" @click="executeRequest(scope.row)" 
                     v-if="userRole === '档案管理员' && scope.row.status === 'approved'">
            执行
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-size="pageSize"
      :total="total"
      layout="total, prev, pager, next">
    </el-pagination>

    <!-- 提交修改申请对话框 -->
    <el-dialog title="提交档案内容修改申请" :visible.sync="submitDialogVisible" width="600px">
      <el-form :model="requestForm" :rules="requestRules" ref="requestForm">
        <el-form-item label="选择档案" prop="archiveId">
          <el-select v-model="requestForm.archiveId" placeholder="请选择档案" style="width: 100%">
            <el-option
              v-for="archive in archives"
              :key="archive.archiveId"
              :label="archive.title"
              :value="archive.archiveId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="修改后的档案内容" prop="modifyContent">
          <el-input type="textarea" :rows="8" v-model="requestForm.modifyContent" 
                    placeholder="请输入修改后的档案内容（将覆盖原有的OCR内容）"></el-input>
        </el-form-item>
        <el-alert
          title="提示：审批通过后，此内容将直接覆盖档案的原有内容"
          type="info"
          :closable="false"
          show-icon>
        </el-alert>
      </el-form>
      <div slot="footer">
        <el-button @click="submitDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitRequest">提交</el-button>
      </div>
    </el-dialog>

    <!-- 查看申请详情对话框 -->
    <el-dialog title="申请详情" :visible.sync="viewDialogVisible" width="800px">
      <div v-if="currentRequest">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="档案标题">{{ currentRequest.archiveTitle }}</el-descriptions-item>
          <el-descriptions-item label="申请人">{{ currentRequest.applicantName }}</el-descriptions-item>
          <el-descriptions-item label="申请时间">{{ formatDate(currentRequest.applyTime) }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="getStatusType(currentRequest.status)">
              {{ getStatusText(currentRequest.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="修改后的内容" :span="2">
            <el-input
              type="textarea"
              :rows="6"
              v-model="currentRequest.modifyContent"
              :readonly="true"
              placeholder="无修改内容">
            </el-input>
          </el-descriptions-item>
          <el-descriptions-item label="审批人" v-if="currentRequest.approverName">
            {{ currentRequest.approverName }}
          </el-descriptions-item>
          <el-descriptions-item label="审批时间" v-if="currentRequest.approveTime">
            {{ formatDate(currentRequest.approveTime) }}
          </el-descriptions-item>
          <el-descriptions-item label="审批意见" :span="2" v-if="currentRequest.approveRemark">
            {{ currentRequest.approveRemark }}
          </el-descriptions-item>
          <el-descriptions-item label="执行人" v-if="currentRequest.executorName">
            {{ currentRequest.executorName }}
          </el-descriptions-item>
          <el-descriptions-item label="执行时间" v-if="currentRequest.executeTime">
            {{ formatDate(currentRequest.executeTime) }}
          </el-descriptions-item>
          <el-descriptions-item label="执行备注" :span="2" v-if="currentRequest.executeRemark">
            {{ currentRequest.executeRemark }}
          </el-descriptions-item>
        </el-descriptions>
        
        <!-- 档案详细信息 -->
        <div v-if="currentArchiveDetails" class="archive-details-section">
          <h4>相关档案信息</h4>
          <el-descriptions :column="2" border size="small">
            <el-descriptions-item label="档案ID">{{ currentArchiveDetails.archiveId }}</el-descriptions-item>
            <el-descriptions-item label="档案类型">{{ currentArchiveDetails.archiveType }}</el-descriptions-item>
            <el-descriptions-item label="保密等级">{{ currentArchiveDetails.securityLevel }}</el-descriptions-item>
            <el-descriptions-item label="物理位置">{{ currentArchiveDetails.physicalLocation }}</el-descriptions-item>
            <el-descriptions-item label="可见范围">{{ currentArchiveDetails.visibleScope }}</el-descriptions-item>
            <el-descriptions-item label="创建时间">{{ currentArchiveDetails.createdAt }}</el-descriptions-item>
          </el-descriptions>
          
          <!-- 文档内容展示 -->
          <div class="ocr-content-section" v-if="currentArchiveDetails.ocrContent">
            <h5>档案原有内容</h5>
            <el-input
              type="textarea"
              :rows="6"
              v-model="currentArchiveDetails.ocrContent"
              :readonly="true"
              placeholder="无文档内容">
            </el-input>
          </div>
          <div class="ocr-content-section" v-else>
            <h5>档案原有内容</h5>
            <el-alert
              title="该档案没有原有内容"
              type="info"
              :closable="false"
              show-icon>
            </el-alert>
          </div>
        </div>
      </div>
    </el-dialog>

    <!-- 审批对话框 -->
    <el-dialog title="审批申请" :visible.sync="approveDialogVisible" width="500px">
      <el-form :model="approveForm" ref="approveForm">
        <el-form-item label="审批结果">
          <el-radio-group v-model="approveForm.status">
            <el-radio label="approved">通过</el-radio>
            <el-radio label="rejected">拒绝</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="审批意见">
          <el-input type="textarea" :rows="4" v-model="approveForm.remark"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="approveDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitApproval">提交</el-button>
      </div>
    </el-dialog>

    <!-- 执行对话框 -->
    <el-dialog title="执行修改" :visible.sync="executeDialogVisible" width="500px">
      <el-form :model="executeForm" ref="executeForm">
        <el-form-item label="执行备注">
          <el-input type="textarea" :rows="4" v-model="executeForm.executeRemark" 
                    placeholder="请说明具体的修改执行情况"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="executeDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitExecution">完成执行</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import service from '@/utils/request'

export default {
  name: 'ArchiveModificationManagement',
  data() {
    return {
      requests: [],
      archives: [],
      loading: false,
      currentPage: 1,
      pageSize: 10,
      total: 0,
      userRole: '',
      userId: null,
      submitDialogVisible: false,
      viewDialogVisible: false,
      approveDialogVisible: false,
      executeDialogVisible: false,
      currentRequest: null,
      currentArchiveDetails: null,
      requestForm: {
        archiveId: '',
        modifyContent: '',
        applicantId: null
      },
      requestRules: {
        archiveId: [
          { required: true, message: '请选择档案', trigger: 'change' }
        ],
        modifyContent: [
          { required: true, message: '请输入修改后的档案内容', trigger: 'blur' }
        ]
      },
      approveForm: {
        status: 'approved',
        remark: ''
      },
      executeForm: {
        executeRemark: ''
      }
    }
  },
  created() {
    const user = JSON.parse(localStorage.getItem('user') || '{}');
    if (user && user.role) {
      this.userRole = user.role;
      this.userId = user.userId;
      this.requestForm.applicantId = user.userId;
    }
  },
  mounted() {
    this.loadRequests()
    this.loadArchives()
  },
  methods: {
    async loadRequests() {
      this.loading = true
      try {
        const response = await service.get(`/api/archive-modification-requests/page?current=${this.currentPage}&size=${this.pageSize}`)
        if (response.data.code === 200) {
          this.requests = response.data.data.records
          this.total = response.data.data.total
        }
      } catch (error) {
        this.$message.error('加载申请列表失败')
      }
      this.loading = false
    },
    
    async loadArchives() {
      try {
        const response = await service.get('/archive/list?pageNum=1&pageSize=10000')
        if (response.data.code === 200) {
          this.archives = response.data.data.records
        }
      } catch (error) {
        console.error('加载档案列表失败', error)
      }
    },
    
    showSubmitDialog() {
      this.submitDialogVisible = true
      this.requestForm = {
        archiveId: '',
        modifyContent: '',
        applicantId: this.userId
      }
    },
    
    async submitRequest() {
      this.$refs.requestForm.validate(async (valid) => {
        if (valid) {
          try {
            const response = await service.post('/api/archive-modification-requests/submit', this.requestForm)
            if (response.data.code === 200) {
              this.$message.success('提交成功')
              this.submitDialogVisible = false
              this.loadRequests()
            } else {
              this.$message.error(response.data.message)
            }
          } catch (error) {
            this.$message.error('提交失败')
          }
        }
      })
    },
    
    viewRequest(request) {
      this.currentRequest = request
      this.viewDialogVisible = true
      // 获取档案详细信息
      this.fetchArchiveDetails(request.archiveId)
    },
    
    async fetchArchiveDetails(archiveId) {
      try {
        const response = await service.get(`/archive/list?pageNum=1&pageSize=1&search=${archiveId}`)
        if (response.data.code === 200 && response.data.data.records.length > 0) {
          this.currentArchiveDetails = response.data.data.records.find(archive => archive.archiveId === archiveId)
        }
      } catch (error) {
        console.error('获取档案详情失败', error)
      }
    },
    
    approveRequest(request) {
      this.currentRequest = request
      this.approveForm = {
        status: 'approved',
        remark: ''
      }
      this.approveDialogVisible = true
    },
    
    async submitApproval() {
      try {
        const response = await service.put(`/api/archive-modification-requests/approve/${this.currentRequest.modRequestId}`, null, {
          params: {
            status: this.approveForm.status,
            remark: this.approveForm.remark,
            approverId: this.userId
          }
        })
        if (response.data.code === 200) {
          this.$message.success('审批成功')
          this.approveDialogVisible = false
          this.loadRequests()
        } else {
          this.$message.error(response.data.message)
        }
      } catch (error) {
        this.$message.error('审批失败')
      }
    },
    
    executeRequest(request) {
      this.currentRequest = request
      this.executeForm = {
        executeRemark: ''
      }
      this.executeDialogVisible = true
    },
    
    async submitExecution() {
      try {
        const response = await service.put(`/api/archive-modification-requests/execute/${this.currentRequest.modRequestId}`, null, {
          params: {
            executeRemark: this.executeForm.executeRemark,
            executorId: this.userId
          }
        })
        if (response.data.code === 200) {
          this.$message.success('执行完成')
          this.executeDialogVisible = false
          this.loadRequests()
        } else {
          this.$message.error(response.data.message)
        }
      } catch (error) {
        this.$message.error('执行失败')
      }
    },
    
    handleCurrentChange(page) {
      this.currentPage = page
      this.loadRequests()
    },
    
    formatDate(dateStr) {
      if (!dateStr) return ''
      return new Date(dateStr).toLocaleString()
    },
    
    getStatusType(status) {
      const typeMap = {
        'pending': 'warning',
        'approved': 'success',
        'rejected': 'danger',
        'completed': 'info'
      }
      return typeMap[status] || 'info'
    },
    
    getStatusText(status) {
      const textMap = {
        'pending': '待审批',
        'approved': '已批准',
        'rejected': '已拒绝',
        'completed': '已完成'
      }
      return textMap[status] || status
    }
  }
}
</script>

<style scoped>
.modification-management {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-buttons {
  display: flex;
  gap: 10px;
}

.el-pagination {
  margin-top: 20px;
  text-align: center;
}

.archive-details-section {
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #e6e6e6;
}

.archive-details-section h4 {
  margin-bottom: 15px;
  color: #606266;
}

.ocr-content-section {
  margin-top: 15px;
}

.ocr-content-section h5 {
  margin-bottom: 10px;
  color: #606266;
  font-size: 14px;
}

.modify-content-preview {
  display: inline-block;
  max-width: 100%;
  word-break: break-all;
  line-height: 1.4;
}
</style> 